package com.android.wordbook;
//recyclerview参考代码https://www.jianshu.com/p/53d692e13bdf
//https://www.jianshu.com/p/8379ea2bc63b

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import java.util.ArrayList;
import java.util.List;

public class WordAdapter extends RecyclerView.Adapter<WordAdapter.ViewHolder>{
    private Activity activity;
    private List<WordItem> list;
    private ItemListener mItemListener;
    public void setItemListener(ItemListener itemListener){
        this.mItemListener = itemListener;
    }
    public WordAdapter(Activity activity){
        this.activity=activity;
        this.list=new ArrayList<>();
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(activity).inflate(R.layout.list_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {
        final WordItem wordItemVo =list.get(position);
        if (wordItemVo !=null){
            holder.tvWord.setText(wordItemVo.getWord());
            holder.tvNote.setText(wordItemVo.getNote());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mItemListener!=null){
                        mItemListener.ItemClick(wordItemVo);
                    }
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (mItemListener!=null){
                        mItemListener.ItemLongClick(wordItemVo);
                    }
                    return false;
                }
            });
        }
    }
    @Override
    public int getItemCount() {
        return list.size();
    }
    public void addItem(List<WordItem> listAdd) {
        //如果是加载第一页，需要先清空数据列表
        this.list.clear();
        if (listAdd!=null){
            //添加数据
            this.list.addAll(listAdd);
        }
        //通知RecyclerView进行改变整体
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tvWord;//单词
        private TextView tvNote;//单词注释
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvWord=itemView.findViewById(R.id.tv_word);
            tvNote=itemView.findViewById(R.id.tv_note);
        }
    }


    public interface ItemListener{
        void ItemClick(WordItem wordItem);
        void ItemLongClick(WordItem wordItem);
    }
}
